package com.sk.weichat.ui.me.wallet;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.SmsCodeForIdentifyActivity;
import com.sk.weichat.util.LiveDataBus;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.PasswordInputEditText;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

import static com.sk.weichat.ui.me.wallet.ResetPayPwdNewActivity.FIRST_SET_PSWD;


public class ResetPayPwdOldActivity extends BaseActivity {
    PasswordInputEditText edtPswd;

    //输错5次的错误码
    private final static int Incorrect_Five_Times_Code = 1040313;

   // private final static String event_request_sms = "ResetPayPwdOldActivity_event_request_sms";
    private final static String event_request_alipay_auth = "ResetPayPwdOldActivity_event_request_alipay_auth";
    private final static int request_reset_pay_pswd = 1255;

    private String type = "";
    private String alipayname = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_pay_pwd_old);
        alipayname = getIntent() != null ? getIntent().getStringExtra("aliPayNickName") : "";
        edtPswd = findViewById(R.id.edt_pswd);
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.reset_pwd_title));
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        edtPswd.setTextWatcher(new Observer<CharSequence>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CharSequence charSequence) {
                String pswd = charSequence.toString();
                if (pswd.length() == 6) {
                    check(pswd, coreManager.getSelfStatus().accessToken);
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        LiveDataBus.get().with(ResetPayPwdOldActivity.this.hashCode() + "").observe(this, new android.arch.lifecycle.Observer<Object>() {

            @Override
            public void onChanged(@Nullable Object o) {
                //
                //找回密码，短信验证成功，跳转实名信息或者忘记密码
                if (type.equals(AppConstant.SET_PAY_PASSWORD_TYPE_ALIPAY)) {
                    //通过支付宝设置的支付密码
                    AlipayAuthActivity.startAlipayAuthActivity(alipayname, event_request_alipay_auth, ResetPayPwdOldActivity.this);
                } else if (type.equals(AppConstant.SET_PAY_PASSWORD_TYPE_ALIYUN)) {
                    //通过实名认证设置的支付密码
                    startActivity(new Intent(mContext, VerifyRealNameInfoActivity.class));
                }
            }

        });
        LiveDataBus.get().with(event_request_alipay_auth).observe(this, new android.arch.lifecycle.Observer<Object>() {

            @Override
            public void onChanged(@Nullable Object o) {
                //支付宝授权认证成功，跳转重置密码
                startActivityForResult(new Intent(mContext, ResetPayPwdNewActivity.class), request_reset_pay_pswd);
            }
        });
    }

    //验证旧密码
    private void check(String pswd, String access_token) {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("language", language);
        params.put("oldPassword", pswd);
        params.put("access_token", access_token);
        HttpUtils.post().url(coreManager.getConfig().CHECK_PASSWORD_FOR_RESET_PASSWORD)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        if (result.getResultCode() == 1) {
                            Intent intent = new Intent(mContext, ResetPayPwdNewActivity.class);
                            intent.putExtra(FIRST_SET_PSWD, true);
                            //验证旧密码成功
                            startActivityForResult(intent, request_reset_pay_pswd);
                        } else if (result.getResultCode() == Incorrect_Five_Times_Code) {
                            failedMsg = result.getResultMsg();
                            //回答错误达到5次
                            setupIncorrectDialog();
                            selectionFrame.show();
                        } else {
                            edtPswd.setText("");
                            //验证旧密码失败
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });


    }

    SelectionFrame selectionFrame;

    String failedMsg = "";

    private void setupIncorrectDialog() {
//
        selectionFrame = new SelectionFrame(this);
        selectionFrame.setSomething(null, failedMsg, "取消", "忘记密码", new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {
                selectionFrame.dismiss();
            }

            @Override
            public void confirmClick() {
                //找回密码 ，获取用户设置支付密码的方式
                getSetPasswordType(coreManager.getSelfStatus().accessToken);
            }
        });
    }

    //获取用户设置支付密码的方式
    private void getSetPasswordType(String access_token) {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("language", language);
        params.put("access_token", access_token);
        HttpUtils.post().url(coreManager.getConfig().GET_SET_PAY_PASSWORD_TYPE)
                .params(params)
                .build()
                .execute(new BaseCallback<String>(String.class) {

                    @Override
                    public void onResponse(ObjectResult<String> result) {
                        if (result.getResultCode() == 1) {
                            type = result.getData();
                            //短信认证
                            SmsCodeForIdentifyActivity.startSmsCodeForIdentifyActivity(ResetPayPwdOldActivity.this.hashCode()+"", mContext);
                        } else {

                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == request_reset_pay_pswd && resultCode == Activity.RESULT_OK) {
            finish();
        }
    }


}


